package com.example.yin.controller;

import com.example.yin.common.ErrorMessage;
import com.example.yin.common.FatalMessage;
import com.example.yin.common.SuccessMessage;
import com.example.yin.config.OSSConfiguration;
import com.example.yin.constant.Constants;
import com.example.yin.domain.Article;
import com.example.yin.domain.Articlelike;
import com.example.yin.domain.Subscribe;
import com.example.yin.service.ArticleService;
import com.example.yin.service.ArticlelikeService;
import com.example.yin.service.OssService;
import com.example.yin.utils.RedisCache;
import com.example.yin.vo.ArticleVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author
 * @description
 * @createDate 2023/6/26
 */

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @Autowired
    private OSSConfiguration ossConfiguration;

    @Autowired
    private OssService ossService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticlelikeService articlelikeService;

    private ConcurrentHashMap<Integer, List<Integer>> likeMap = new ConcurrentHashMap<>();

//    @Bean
//    public MultipartConfigElement multipartConfigElement() {
//        MultipartConfigFactory factory = new MultipartConfigFactory();
//        // 文件最大10M,DataUnit提供5中类型B,KB,MB,GB,TB
//        factory.setMaxFileSize(DataSize.of(20, DataUnit.MEGABYTES));
//        // 设置总上传数据总大小10M
//        factory.setMaxRequestSize(DataSize.of(20, DataUnit.MEGABYTES));
//        return factory.createMultipartConfig();
//    }

    @Configuration
    public static class MyPicConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/img/articlePic/**")
                    .addResourceLocations(Constants.ARTICLE_PIC_PATH);
            registry.addResourceHandler("/song/**")
                    .addResourceLocations(Constants.ARTICLE_PIC_PATH);
        }
    }


    @ResponseBody
    @RequestMapping(value = "/articlePic/add/test", method = RequestMethod.POST)
    public Object addPic(HttpServletRequest req, @RequestParam("file") MultipartFile mpfile) {
        String name = req.getParameter("name").trim();
        ossService.uploadFile(mpfile,"test/"+name+".jpg");
        return new SuccessMessage<String>("上传成功").getMessage();
    }

    //读一次增加一个浏览量

    @RequestMapping(value = "/read", method = RequestMethod.GET)
    public Object read(Integer article_id){
        Integer res = 0;
        if(redisCache.getCacheObject("Article:"+article_id)==null){
            res = articleService.getDetail(article_id).getRead_count();
            res++;
            redisCache.setCacheObject("Article:"+article_id,res);
        }
        else{
            res = redisCache.getCacheObject("Article:"+article_id);
            res++;
            redisCache.setCacheObject("Article:"+article_id,res);
        }
        return new SuccessMessage<Integer>("成功", res).getMessage();
    }


    //点赞接口
//    @RequestMapping(value = "/like", method = RequestMethod.GET)
//    public Object like(Integer article_id, Consumer consumer){
//        List<Integer> consumerList = likeMap.getOrDefault(article_id, new ArrayList<>());
//        Article detail = articleService.getDetail(article_id);
//        if (consumerList.contains(consumer.getId())){
//            detail.setLike_count(detail.getLike_count()-1);
//            boolean res = articleService.update(detail);
//            if (res) {
//                consumerList.remove(consumer.getId());
//                return new SuccessMessage<ObjectUtils.Null>("取消点赞成功").getMessage();
//            }
//        }else {
//            detail.setLike_count(detail.getLike_count()+1);
//            boolean res = articleService.update(detail);
//            if (res) {
//                consumerList.add(consumer.getId());
//                return new SuccessMessage<ObjectUtils.Null>("点赞成功").getMessage();
//            }
//        }
//        return new ErrorMessage("点赞失败").getMessage();
//    }


    @RequestMapping(value = "/like", method = RequestMethod.GET)
    public Object like(Integer article_id,Integer user_id){

        Integer res = 0;
        if(redisCache.getCacheObject("like"+article_id)==null){
            res=articleService.getDetail(article_id).getLike_count();
            redisCache.setCacheObject("like"+article_id,res);
        }
        else{
            res=redisCache.getCacheObject("like"+article_id);
        }

        Integer v = redisCache.getCacheObject("Articlelike"+user_id+":"+article_id);
        if(v==null){
            Articlelike articlelike = articlelikeService.searchbyKey(user_id,article_id);

            if(articlelike!=null&&articlelike.getIslike()!=null){
                redisCache.setCacheObject("Articlelike"+user_id+":"+article_id,0);
                redisCache.setCacheObject("like"+article_id,res-1);
                return new SuccessMessage<Integer>("取消点赞成功",res-1).getMessage();
            }
            else{
                redisCache.setCacheObject("Articlelike"+user_id+":"+article_id,1);
                redisCache.setCacheObject("like"+article_id,res+1);
                return new SuccessMessage<Integer>("点赞成功",res+1).getMessage();
            }

        }
        else if(v==0){
            redisCache.setCacheObject("Articlelike"+user_id+":"+article_id,1);
            redisCache.setCacheObject("like"+article_id,res+1);
            return new SuccessMessage<Integer>("点赞成功",res+1).getMessage();
        }
        else{
            redisCache.setCacheObject("Articlelike"+user_id+":"+article_id,0);
            redisCache.setCacheObject("like"+article_id,res-1);
            return new SuccessMessage<Integer>("取消点赞成功",res-1).getMessage();

        }

//        List<Integer> consumerList = likeMap.getOrDefault(article_id, new ArrayList<>());

//        Article detail = articleService.getDetail(article_id);
//        if (consumerList.contains(user_id)){
//            detail.setLike_count(detail.getLike_count()-1);
//            boolean res = articleService.update(detail);
//            if (res) {
//                consumerList.remove(user_id);
//                return new SuccessMessage<ObjectUtils.Null>("取消点赞成功").getMessage();
//            }
//        }else {
//            detail.setLike_count(detail.getLike_count()+1);
//            boolean res = articleService.update(detail);
//            if (res) {
//                consumerList.add(Integer.valueOf(user_id));
//                return new SuccessMessage<ObjectUtils.Null>("点赞成功").getMessage();
//            }
//        }
        //return new ErrorMessage("点赞失败").getMessage();
    }

//    @RequestMapping(value = "/like", method = RequestMethod.GET)
//    public Object like(Integer article_id, Consumer consumer){
//        List<Integer> consumerList = likeMap.getOrDefault(article_id, new ArrayList<>());
//        Article detail = articleService.getDetail(article_id);
//        if (consumerList.contains(consumer.getId())){
//            detail.setLike_count(detail.getLike_count()-1);
//            boolean res = articleService.update(detail);
//            if (res) {
//                consumerList.remove(consumer.getId());
//                return new SuccessMessage<ObjectUtils.Null>("取消点赞成功").getMessage();
//            }
//        }else {
//            detail.setLike_count(detail.getLike_count()+1);
//            boolean res = articleService.update(detail);
//            if (res) {
//                consumerList.add(consumer.getId());
//                return new SuccessMessage<ObjectUtils.Null>("点赞成功").getMessage();
//            }
//        }
//        return new ErrorMessage("点赞失败").getMessage();
//    }



//    @ResponseBody
//    @RequestMapping(value = "/comment/like", method = RequestMethod.POST)
//    public Object commentOfLike(HttpServletRequest req) {
//        String id = req.getParameter("id").trim();
//        String up = req.getParameter("up").trim();
//        String user_id = req.getParameter("user_id").trim();
//        Comment comment = new Comment();
//        comment.setId(Integer.parseInt(id));
//        comment.setUp(Integer.parseInt(up));
//        Consumer consumer = new Consumer();
//        consumer.setId(Integer.parseInt(user_id));
//        boolean res = commentService.updateCommentMsg(comment,consumer);
//        if (res) {
//            return new SuccessMessage<ObjectUtils.Null>("点赞成功").getMessage();
//        } else {
//            return new ErrorMessage("点赞失败").getMessage();
//        }
//    }


    @RequestMapping("/add")
    public Object add(HttpServletRequest req, @RequestParam("file") MultipartFile mpfile){
        //从请求中获取
        String article_user = req.getParameter("article_user").trim();
        String article_title = req.getParameter("article_title").trim();
        String like_count = req.getParameter("like_count").trim();
        String read_count = req.getParameter("read_count").trim();
        String top_flag = req.getParameter("top_flag").trim();
        String article_summary = req.getParameter("article_summary").trim();
        String content_html = req.getParameter("content_html").trim();
//        String pic = "/img/songPic/tubiao.jpg";
        String article_description = req.getParameter("article_description").trim();

        String fileName = mpfile.getOriginalFilename();
        String storeUrlPath = ossConfiguration.getArticlePicFilePath()+fileName;
        //上传oss
        ossService.uploadFile(mpfile,ossConfiguration.getArticlePicFilePath()+fileName);
        //存数据库
        Article article = new Article();
        article.setArticle_data(new Date());
        article.setArticle_user(Integer.valueOf(article_user));
        article.setArticle_title(article_title);
        article.setLike_count(Integer.valueOf(like_count));
        article.setRead_count(Integer.valueOf(read_count));
        article.setTop_flag(top_flag);
        article.setArticle_summary(article_summary);
        article.setContent_html(content_html);
        article.setArticle_description(article_description);
        article.setArticle_picture(storeUrlPath);
        boolean res = articleService.add(article);
        if (res) {
            return new SuccessMessage<ObjectUtils.Null>("添加成功").getMessage();
        } else {
            return new ErrorMessage("添加失败").getMessage();
        }
    }

    @RequestMapping("/delete")
    public Object delete(Integer article_id){
        boolean res = articleService.delete(article_id);
        if (res) {
            return new SuccessMessage<ObjectUtils.Null>("删除成功").getMessage();
        } else {
            return new ErrorMessage("删除失败").getMessage();
        }
    }

    @RequestMapping("/update")
    public Object update(@RequestBody Article article){
        boolean res = articleService.update(article);
        if (res) {
            return new SuccessMessage<ObjectUtils.Null>("更新成功").getMessage();
        } else {
            return new ErrorMessage("更新失败").getMessage();
        }
    }



    // 更新文章图片
    @ResponseBody
    @RequestMapping(value = "/img/update", method = RequestMethod.POST)
    public Object updateSongPic(@RequestParam("file") MultipartFile urlFile, @RequestParam("id") int id) {
        String fileName = System.currentTimeMillis() + urlFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator") + "articelPic";
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeUrlPath = "/img/articlePic/" + fileName;
        try {
            urlFile.transferTo(dest);
            Article article = new Article();
            article.setArticle_id(id);
            article.setArticle_picture(storeUrlPath);
            boolean res = articleService.updateArticlePic(article);
            if (res) {
                return new SuccessMessage<String>("上传成功", storeUrlPath).getMessage();
            } else {
                return new ErrorMessage("上传失败").getMessage();
            }
        } catch (IOException e) {
            return new FatalMessage("上传失败" + e.getMessage()).getMessage();
        }
    }

    @RequestMapping(value = "/subscribe",method = RequestMethod.POST)
    public Object Subscribe(HttpServletRequest req) {
        String user_id = req.getParameter("user_id");
        String sub_user_id = req.getParameter("sub_user_id");
        Integer uid = Integer.parseInt(user_id);
        Integer suid = Integer.parseInt(sub_user_id);
        Subscribe subscribe = new Subscribe();
        subscribe.setSub_user_id(suid);
        subscribe.setUser_id(uid);
        if (articleService.isExist(uid, suid)) {
            articleService.deleteSubscribe(uid, suid);
            return new SuccessMessage("取消订阅成功").getMessage();
        } else {
            boolean res = articleService.subscribe(subscribe);
            if (res) {
                return new SuccessMessage("订阅成功").getMessage();
            } else {
                return new ErrorMessage("订阅失败").getMessage();
            }
        }
    }
//        boolean res = articleService.subscribe(subscribe);
//        if (res) {
//            if(articleService.isExist(uid,suid)){
//
//                articleService.deleteSubscribe(uid,suid);
//                return new SuccessMessage("取消订阅成功").getMessage();
//            }else{
//                articleService.insertIntoSubscribe(uid,suid);
//                return new SuccessMessage("订阅成功").getMessage();
//            }
//        } else {
//            return new ErrorMessage("订阅失败").getMessage();
//        }


//    @RequestMapping(value = "/like", method = RequestMethod.GET)
//    public Object like(String article_id, String user_id){
//        Integer articleId = Integer.valueOf(article_id);
//        Integer userId = Integer.valueOf(user_id);
//        List<Integer> consumerList = likeMap.getOrDefault(articleId, new ArrayList<>());
//        likeMap.put(articleId,consumerList);
//        Article detail = articleService.getDetail(Integer.valueOf(articleId));
//        if (consumerList.contains(userId)){
//            detail.setLike_count(detail.getLike_count()-1);
//            boolean res = articleService.update(detail);
//            if (res) {
//                consumerList.remove(userId);
//                return new SuccessMessage<ObjectUtils.Null>("取消点赞成功").getMessage();
//            }
//        }else {
//            detail.setLike_count(detail.getLike_count()+1);
//            boolean res = articleService.update(detail);
//            if (res) {
//                consumerList.add(userId);
//                return new SuccessMessage<ObjectUtils.Null>("点赞成功").getMessage();
//            }
//        }
//        return new ErrorMessage("点赞失败").getMessage();
//    }


    @RequestMapping(value = "/getsubarticle",method = RequestMethod.GET)
    public Object getSubArticle(@RequestParam("user_id") int user_id){
        List<Article> res = articleService.getSubArticle(user_id);
        if (res !=null) {
            return new SuccessMessage<List<Article>>("加载成功",res).getMessage();
        } else {
            return new ErrorMessage("加载失败").getMessage();
        }
    }
    @RequestMapping("/detail")
    public Object getDetail(Integer article_id){
        Article res = articleService.getDetail(article_id);
        if (res != null) {
            return new SuccessMessage("查询成功",res).getMessage();
        } else {
            return new ErrorMessage("查询失败").getMessage();
        }
    }

    @RequestMapping("/list/test")
    public Object getList(@RequestBody Article article){
        List<Article> res = articleService.getList(article);
        if (res != null) {
            return new SuccessMessage("查询成功",res).getMessage();
        } else {
            return new ErrorMessage("查询失败").getMessage();
        }
    }

    @RequestMapping("/list")
    public Object getListVO(@RequestBody ArticleVO articleVO){
        Integer userId = articleVO.getUserId();
        List<ArticleVO> res = articleService.getListVO(articleVO);
        for(ArticleVO vo:res){
            if(vo.getIslike()!=null){
                redisCache.setCacheObject("Articlelike"+userId+":"+vo.getArticle_id(),1);
            }
        }
        if (res != null) {
            return new SuccessMessage("查询成功",res).getMessage();
        } else {
            return new ErrorMessage("查询失败").getMessage();
        }
    }


    // 更新文章图片
//    @ResponseBody
//    @RequestMapping(value = "/song/img/update", method = RequestMethod.POST)
//    public Object updateSongPic(@RequestParam("file") MultipartFile urlFile, @RequestParam("id") int id) {
//        String fileName = System.currentTimeMillis() + urlFile.getOriginalFilename();
//        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator") + "songPic";
//        File file1 = new File(filePath);
//        if (!file1.exists()) {
//            file1.mkdir();
//        }
//
//        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
//        String storeUrlPath = "/img/songPic/" + fileName;
//        try {
//            urlFile.transferTo(dest);
//            Song song = new Song();
//            song.setId(id);
//            song.setPic(storeUrlPath);
//            boolean res = songService.updateSongPic(song);
//            if (res) {
//                return new SuccessMessage<String>("上传成功", storeUrlPath).getMessage();
//            } else {
//                return new ErrorMessage("上传失败").getMessage();
//            }
//        } catch (IOException e) {
//            return new FatalMessage("上传失败" + e.getMessage()).getMessage();
//        }
//    }

}
